/*
 * Agenda.c
 * 
 * Copyright 2014 gabo <gabo@tux>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 * 
 */

#include <stdio.h>
#include <stdlib.h>

struct agenda{
	char nom[15];
	char ape[15];
	long tel;
};

typedef struct agenda ag;

void agregar();
int listar();

FILE * file;

int op;
char re;

int main( void )
{
	do{
		
		puts( "\t\t\t\tAGENDA\n" );
		printf( "\n1. Agregar contacto " );
		printf( "\n2. Ver contactos " );
		printf( "\n3. Salir " );
		printf( "\n\nElija una opcion: " );
		scanf( "%d", &op );
		
		switch( op )
		{
			
			case 1: agregar();
				break;
				
			case 2: listar();
				break;
				
			case 3: puts( "Saliendo..." ); exit( 0 );
				break;
				
			default: puts( "Opcion invalida" );
				break;
			
			}
		
		
		
		}while( op != 3 );
	
	return 0;
}


void agregar()
{
	system( "clear" ); // si usas Windows cambiar "clear" por "cls"
	ag c1;
	
	file = fopen( "agenda.txt", "ab" );
	if( file == NULL )
		puts( "Error al abrir archivo" );
		
	else
	{
		printf( "Nombre: " );
		scanf( "%s", c1.nom );
		printf( "\nApellido: " );
		scanf( "%s", c1.ape );
		printf( "\nTelefono: " );
		scanf( "%ld", &c1.tel );
		
		printf( "\n¿ Guardar los cambios ? [s/n] " );
		scanf( "%s", &re );
		
		if( re == 's' || re == 'S' )
		{
			fwrite(&c1, sizeof(ag), 1, file );
			puts( "Los datos se guardaron correctamente !" );
			}
		else
			puts( "Los datos no se guardaron !" );
		}
	fclose(file);
}


int listar()
{

	system( "clear" );
	ag c1;
	
	file = fopen( "agenda.txt", "rb" );
	
	if( file == NULL )
		puts( "Error al abrir archivo" );
		
	else
	{
		fread(&c1, sizeof(ag), 1, file);
		while( !feof(file))
		{
			printf( "\n%s", c1.nom );
			printf( "\n%s", c1.ape );
			printf( "\n%ld\n", c1.tel );
			
			fread(&c1, sizeof(ag), 1, file );
			
			}
		printf( "\n¿ Volver al menu ? [s/n] " );
		scanf( "%s", &re );
		
		if( re == 's' || re == 'S' )
			return main();
		else
			{
				puts( "Saliendo..." );
				exit( 0 );
				}
		}
	fclose(file);
return 0;
}
